package com.wenlin.myproduction.ui;

import android.content.Context;
import android.view.ViewGroup;

import com.wenlin.myproduction.R;
import com.wenlin.myproduction.base.AbsViewHolder;
import com.wenlin.myproduction.bean.LabelBean;
import com.wenlin.myproduction.util.Checker;
import com.wenlin.myproduction.util.UI;
import com.wenlin.myproduction.widget.LabelsView;

import java.util.LinkedList;
import java.util.List;

/**
 *
 */
public class LabelsViewHolder extends AbsViewHolder {
    private LabelsView lv;
    private List<LabelBean> list;
    private LinkedList<LabelBean> labelsSelected;
    private int maxSelectedNum;

    public LabelsViewHolder(Context context, ViewGroup parentView) {
        super(context, parentView);
    }

    public LabelsViewHolder(Context context, ViewGroup parentView, Object... args) {
        super(context, parentView, args);
    }

    @Override
    protected void processArguments(Object... args) {
        super.processArguments(args);
        maxSelectedNum = (int) args[0];
        list = (List<LabelBean>) args[1];
    }

    @Override
    protected int getLayoutId() {
        return R.layout.view_labels;
    }

    @Override
    public void init() {
        initView();
        labelsSelected = new LinkedList<>();
        if (Checker.hasList(list)) {
            UI.setLabels(lv, list, 4, true, labelBean -> {
                if (labelBean.isSelected()) {
                    if (!labelsSelected.contains(labelBean)) {
                        labelsSelected.add(labelBean);
                        if (labelsSelected.size() > maxSelectedNum) {
                            LabelBean first = labelsSelected.get(0);
                            if (list.contains(first)) lv.setUnSelected(first);
                            labelsSelected.remove(0);
                        }
                    }
                } else {
                    for (int i = 0; i < labelsSelected.size(); i++) {
                        if (labelBean.getId() == labelsSelected.get(i).getId()) {
                            labelsSelected.remove(i);
                            break;
                        }
                    }
                }
            });
        }
    }

    public LinkedList<LabelBean> getSelectedLabels() {
        return labelsSelected;
    }

    public void resetLabels() {
        if (Checker.hasList(list) && labelsSelected != null && labelsSelected.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                LabelBean temp = list.get(i);
                if (labelsSelected.contains(temp)) {
                    UI.resetTargetLabel(lv, temp);
                }
            }
        }
        if (labelsSelected != null) labelsSelected.clear();
        labelsSelected = new LinkedList<>();
    }

    private void initView() {
        lv = findViewById(R.id.lv);
    }
}
